using System;
using System.Collections.Generic;
using System.Windows.Forms;
using EnvDTE;

namespace Skim.Ssms.AddIn.ActiveFileExplorer.Loader
{
    /// <summary>
    /// Load documents grouped by document type - DocumentType Item, Query, Designer
    /// </summary>
    public class TypeDocumentLoader : DocumentLoader
    {
        protected override void LoadTreeView(TreeView treeView, IEnumerable<Document> documents)
        {
            LoadTreeViewGroup(new DocumentTypeLoaderContext("Queries", treeView,
                DocumentTypeFilter.FilterQueryDocuments(documents), TreeViewImageIndex.QueryGroup));
            LoadTreeViewGroup(new DocumentTypeLoaderContext("Solution Items", treeView,
                DocumentTypeFilter.FilterSolutionDocuments(documents), TreeViewImageIndex.SolutionGroup));
            LoadTreeViewGroup(new DocumentTypeLoaderContext("Designers", treeView,
                DocumentTypeFilter.FilterDesignDocuments(documents), TreeViewImageIndex.DesignGroup));
        }

        private void LoadTreeViewGroup(DocumentTypeLoaderContext context)
        {
            TreeNode groupNode = GetUniqueGroupNode(context.TreeView, context.GroupName);
            groupNode.ImageIndex = GetImageIndex(context.GroupImageIndex);
            AddDocumentsToNodeGroup(context, groupNode);
        }

        private static void AddDocumentsToNodeGroup(DocumentTypeLoaderContext context, TreeNode groupNode)
        {
            Func<Document, int> getImageIndex =
                document => GetImageIndex(DocumentInfoFactory.GetInfo(document).DocumentImageIndex);
            Func<Document, string> getNodeName =
                document => DocumentNameParserFactory.Create(document).GetDocumentName(document);

            foreach (Document document in context.Documents)
            {
                var node = groupNode.Nodes.Add(getNodeName(document));
                node.ImageIndex = getImageIndex(document);
                node.Tag = document;
            }
        }

        private class DocumentTypeLoaderContext
        {
            public string GroupName { get; private set; }
            public TreeView TreeView { get; private set; }
            public IEnumerable<Document> Documents { get; private set; }
            public TreeViewImageIndex GroupImageIndex { get; private set; }

            public DocumentTypeLoaderContext(
                string groupName, TreeView treeView, IEnumerable<Document> documents, TreeViewImageIndex groupImage)
            {
                GroupName = groupName;
                TreeView = treeView;
                Documents = documents;
                GroupImageIndex = groupImage;
            }
        }
    }
}